package com.cn.http.http.impl;

import com.cn.http.http.HttpConfig;
import com.cn.http.http.HttpResponse;
import com.cn.http.http.abstracts.AbstractHttpRequest;
import com.cn.http.utils.MapUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * &#064;Time 2024 八月 星期四 22:09
 *
 * @author ShangGuan
 */
public class SimpleHttpRequest extends AbstractHttpRequest {

    public SimpleHttpRequest(Http http) {
        super(http);
    }

    @Override
    public void config() {
        HttpConfig httpConfig = super.getHttpConfig();
        HttpURLConnection connection = super.getConnection();
        if (httpConfig != null && connection != null) {
            //配置
            Map<String, Object> config = httpConfig.getConfig();
            if (!MapUtils.isEmpty(new HashMap<>(config))) {
                for (String k : config.keySet()) {
                    connection.setRequestProperty(k, String.valueOf(config.get(k)));
                }
            }
        }
        super.setConnection(connection);
    }
    /**
     * 方法会关闭所使用的流，所以请不要手动关闭流
     *
     * @return {@link HttpResponse }
     * @throws IOException IOException
     */
    @Override
    public HttpResponse execute() throws IOException {
        HttpURLConnection httpURLConnection = super.constructConnection();
        int responseCode = httpURLConnection.getResponseCode();
        Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
        InputStream inputStream = httpURLConnection.getInputStream();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            StringBuilder requestBuilder = new StringBuilder();
            String line;
            //读取返回的内容
            while ((line = reader.readLine()) != null) {
                requestBuilder.append(line);
            }
            SimpleHttpResponse simpleHttpResponse = new SimpleHttpResponse();
            simpleHttpResponse.setStatusCode(responseCode);
            simpleHttpResponse.setContent(requestBuilder.toString());
            simpleHttpResponse.setResponseHeaders(headerFields);
            httpURLConnection.disconnect();
            return simpleHttpResponse;
        }
    }


}
